#!/bin/bash

# Fork http://docs.jumpserver.org/zh/docs/step_by_step.html

# 关闭防火墙,Selinux
systemctl stop firewalld
systemctl disable firewalld
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config

# 配置yum源
mkdir /etc/yum.repos.d/OldRepo
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/OldRepo/
curl -so /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo
curl -so /etc/yum.repos.d/Centos-7.repo http://mirrors.aliyun.com/repo/Centos-7.repo
sed -i '/aliyuncs.com/d' /etc/yum.repos.d/Centos-7.repo /etc/yum.repos.d/epel-7.repo

# 时间同步
yum install -y ntpdate
ntpdate ntp1.aliyun.com
hwclock -w
echo "*/20 * * * * $(which ntpdate) ntp1.aliyun.com > /dev/null 2>&1 && $(which hwclock) -w" > /var/spool/cron/root
chmod 600 /var/spool/cron/root

# 快速启动
sed -i 's/timeout=.*/timeout=1/g' /boot/grub2/grub.cfg

# 安装依赖包
yum -y install wget sqlite-devel xz gcc automake zlib-devel openssl-devel epel-release git wget expect

# 编译安装python
# wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz
wget http://192.168.2.7/Python-3.6.1.tar.xz
tar xvf Python-3.6.1.tar.xz  && cd Python-3.6.1
./configure && make && make install

# 配置PIP源
mkdir ~/.pip/
cat <<EOF  >~/.pip/pip.conf
[global]
index-url=http://pypi.mirrors.ustc.edu.cn/simple

[install]
trusted-host=pypi.mirrors.ustc.edu.cn
EOF

# 建立 Python 虚拟环境
cd /opt
python3 -m venv py3
source /opt/py3/bin/activate

# 自动载入 Python 虚拟环境配置
cd /opt
git clone https://github.com/kennethreitz/autoenv.git
echo 'source /opt/autoenv/activate.sh' >> ~/.bashrc
source ~/.bashrc

# 安装 Jumpserver
cd /opt/
git clone https://github.com/jumpserver/jumpserver.git && cd jumpserver && git checkout master
echo "source /opt/py3/bin/activate" > /opt/jumpserver/.env 

# 安装依赖 RPM 包
cd /opt/jumpserver/requirements
yum -y install $(cat rpm_requirements.txt)  # 如果没有任何报错请继续

# 安装 Python 库依赖
pip install -r requirements.txt || mv ~/.pip/pip.conf /tmp
pip install -r requirements.txt && mv /tmp/pip.conf ~/.pip

# 安装 Redis, Jumpserver 使用 Redis 做 cache 和 celery broke
yum -y install redis
systemctl enable redis
systemctl start redis

# 安装 MySQL
yum -y install mariadb mariadb-devel mariadb-server
systemctl enable mariadb
systemctl start mariadb

# 创建数据库 Jumpserver 并授权
mysql
create database jumpserver default charset 'utf8';
grant all on jumpserver.* to 'jumpserver'@'127.0.0.1' identified by 'root';
flush privileges;
exit

# 修改 Jumpserver 配置文件
cd /opt/jumpserver
cp config_example.py config.py

sed -i 's/SECRET_KEY/# SECRET_KEY/' /opt/jumpserver/config.py
sed -i "19i\    SECRET_KEY = \'$(cat /dev/urandom | tr -dc a-z | head -c 50)\'" /opt/jumpserver/config.py
sed -i '28 s/DEBUG/WARNING/' /opt/jumpserver/config.py
sed -i '35,36 s/^    /    # /' /opt/jumpserver/config.py
sed -i '39,44 s/^    # /    /' /opt/jumpserver/config.py
sed -i '43 s/weakPassword/root/' /opt/jumpserver/config.py

# 生成数据库表结构和初始化数据
cd /opt/jumpserver/utils
bash make_migrations.sh

# 运行Jumpserver
cd /opt/jumpserver
./jms start all  # 后台运行使用 -d 参数./jms start all -d

# 浏览器打开
http://IP:8080/ 默认账号: admin 密码: admin

# 安装 SSH Server 和 WebSocket Server: Coco
# 新开一个终端
source /opt/py3/bin/activate
cd /opt
source /opt/py3/bin/activate
git clone https://github.com/jumpserver/coco.git && cd coco && git checkout master
echo "source /opt/py3/bin/activate" > /opt/coco/.env  # 进入 coco 目录时将自动载入 python 虚拟环境

# 安装依赖
cd /opt/coco/requirements
yum -y  install $(cat rpm_requirements.txt)
pip install -r requirements.txt || mv ~/.pip/pip.conf /tmp
pip install -r requirements.txt && mv /tmp/pip.conf ~/.pip

# 修改配置文件并运行
cd /opt/coco
mkdir keys
cp conf_example.py conf.py         # 如果 coco 与 jumpserver 分开部署，请手动修改 conf.py
sed -i '16i\    NAME = "coco"' /opt/coco/conf.py
sed -i "20i\    CORE_HOST = 'http://127.0.0.1:8080'" /opt/coco/conf.py
sed -i "43i\    LOG_LEVEL = 'WARN'" /opt/coco/conf.py

# 启动服务
mkdir /opt/coco/logs
./cocod start  # |stop|status|restart  # 后台运行请添加 -d 参数

# 启动成功后去Jumpserver 会话管理-终端管理（http://10.0.0.11:8080/terminal/terminal/）接受coco的注册


# 安装 Web Terminal 前端: Luna(Luna 已改为纯前端，需要 Nginx 来运行访问)
cd /opt
wget https://github.com/jumpserver/luna/releases/download/1.4.3/luna.tar.gz
tar xvf luna.tar.gz
chown -R root:root luna

#  安装 Windows 支持组件
# 因为手动安装 guacamole 组件比较复杂，这里提供打包好的 docker 使用, 启动 guacamole
yum remove docker-latest-logrotate docker-logrotate docker-selinux dockdocker-engine
yum install -y yum-utils device-mapper-persistent-data lvm2

# 国内部分用户可能无法连接docker官网提供的源，这里提供阿里云的镜像节点供测试使用
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
rpm --import http://mirrors.aliyun.com/docker-ce/linux/centos/gpg
yum makecache fast
yum -y install docker-ce

# 配置docker加速
mkdir /etc/docker
curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://3272dd08.m.daocloud.io

# 启动服务
systemctl start docker
systemctl status docker
systemctl enable docker


# 启动 Guacamole
# 注意：这里需要修改下 http://<填写jumpserver的url地址> 例: http://10.0.0.11:8080, 否则会出错, 带宽有限, 下载时间可能有点长
# 不能使用 127.0.0.1 ，可以更换 registry.jumpserver.org/public/guacamole:latest
docker run --name jms_guacamole -d \
  -p 8081:8080 -v /opt/guacamole/key:/config/guacamole/key \
  -e JUMPSERVER_KEY_DIR=/config/guacamole/key \
  -e JUMPSERVER_SERVER=http://10.0.0.11:8080 \
  jumpserver/guacamole:latest

# 启动成功后去Jumpserver 会话管理-终端管理（http://10.0.0.11:8080/terminal/terminal/）接受[Gua]开头的一个注册

# 配置 Nginx 整合各组件
yum -y install nginx

# 修改配置
cp /etc/nginx/nginx.conf{,.bak}

cat <<'EOF'    >/etc/nginx/nginx.conf
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen 80;  # 代理端口，以后将通过此端口进行访问，不再通过8080端口
        server_name demo.jumpserver.org;  # 修改成你的域名

        client_max_body_size 100m;  # 录像及文件上传大小限制

        location /luna/ {
            try_files $uri / /index.html;
            alias /opt/luna/;  # luna 路径，如果修改安装目录，此处需要修改
        }

        location /media/ {
            add_header Content-Encoding gzip;
            root /opt/jumpserver/data/;  # 录像位置，如果修改安装目录，此处需要修改
        }

        location /static/ {
            root /opt/jumpserver/data/;  # 静态资源，如果修改安装目录，此处需要修改
        }

        location /socket.io/ {
            proxy_pass       http://localhost:5000/socket.io/;  # 如果coco安装在别的服务器，请填写它的ip
            proxy_buffering off;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            access_log off;
        }

        location /coco/ {
            proxy_pass       http://localhost:5000/coco/;  # 如果coco安装在别的服务器，请填写它的ip
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            access_log off;
        }

        location /guacamole/ {
            proxy_pass       http://localhost:8081/;  # 如果guacamole安装在别的服务器，请填写它的ip
            proxy_buffering off;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $http_connection;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            access_log off;
        }

        location / {
            proxy_pass http://localhost:8080;  # 如果jumpserver安装在别的服务器，请填写它的ip
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}
EOF

# 运行 Nginx
nginx -t
systemctl start nginx
systemctl enable nginx

# 开始使用 Jumpserver
# 确定jumpserver已经运行，如果没有运行请重新启动jumpserver
cd /opt/jumpserver
./jms status

# 确定jumpserver已经运行，如果没有运行请重新启动coco
cd /opt/coco
./cocod status

# 如果安装了 Guacamole 检查容器是否已经正常运行，如果没有运行请重新启动Guacamole
docker ps

# 服务全部启动后，访问 http://10.0.0.11，访问nginx代理的端口
# 默认账号: admin 密码: admin


# 测试连接
# 如果登录客户端是 macOS 或 Linux ，登录语法如下
ssh -p2222 admin@10.0.0.11
sftp -P2222 admin@10.0.0.11
# 密码: admin

# 如果登录客户端是 Windows ，Xshell Terminal 登录语法如下
ssh admin@10.0.0.11 2222
sftp admin@10.0.0.11 2222
# 密码: admin
# 如果能登陆代表部署成功

# sftp默认上传的位置在资产的 /tmp 目录下
# windows拖拽上传的位置在资产的 Guacamole RDP上的 G 目录下





# jumpserver服务器重启后启动服务
cd /opt/jumpserver && ./jms start all -d
cd /opt/coco && ./cocod start -d
docker start jms_guacamole



# 给容器添加跟随docker服务启动
# docker update --restart=always jms_guacamole